function seg_map=segment_image(image_gray,sigma,K_th,min_size,disp)

% This function segments a grayscale image and retuns  segmentation map

% Function Inputs:
%-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
% image_gray - grayscale image matrix
%-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
% sigma - Used to smooth the input image before segmenting it.
%-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
% K_th - Value for the threshold function.
%-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
% min_size - Minimum component size enforced by post-processing.
%-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
% disp - display flag of segmentation - writing out the amount of segemnts. for display put something.
%-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

% Function Outputs:
%-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
% seg_map - the segmentation map. 
%-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

if nargin==5
    disp=1;
else 
    disp=0;
end

%setting segmentation command
if (disp)
    segmentation=sprintf('segment %1.1f %d %d image.ppm segment.ppm ',sigma,K_th,min_size);
else
    segmentation=sprintf('segment %1.1f %d %d image.ppm segment.ppm >temp',sigma,K_th,min_size);
end

imwrite(image_gray,'image.ppm');
system(segmentation);
SEG=imread('segment.ppm');

%reshaping the segment map
sze=size(SEG);
temp=reshape(SEG,[sze(1)*sze(2) ,sze(3)]);
[labels,m,n]=unique(temp,'rows');
seg_map=reshape(n,sze(1),sze(2));

%delete temp files
delete ('image.ppm');
delete('segment.ppm');
if (~disp)
    delete ('temp');
end
